import {Checkbox, Image, ScrollView, Text, Textarea, View} from "@tarojs/components";
import {useEffect, useState} from "react";
import Taro from "@tarojs/taro";
import {request} from "../../utils/request";
import {apis} from "../../constants/apis";
import styles from './order_submit.module.scss';
import {CanSelectAddressBack} from "../../envent_bus/events";
import {useEventBusSubscribeDelay} from "../../envent_bus/event_bus";
import globalData from "../../global_data";

const order_submit = () => {
  const [selectProductList, setSelectProductList] = useState<any>([]);
  const [totalPrice, setTotalPrice] = useState(0);
  const [dinnerMethod, setDinnerMethod] = useState<any>(1); //就餐方式：1堂食，0打包
  const [deliveryAddressDetail, setDeliveryAddressDetail] = useState<any>('');
  const setCanSelectAddressBackListener = useEventBusSubscribeDelay<CanSelectAddressBack>(CanSelectAddressBack.eventName);
  const [inputCount, setInputCount] = useState(0);
  const [detail, setDetail] = useState('');
  useEffect(() => {
    (async () => {
      await getSelectProduct();
    })();
  }, [])

  //获取选择商品的列表ID
  const getSelectProduct = async () => {
    let productList: any = Taro.getCurrentInstance().router?.params
    let selectProductIdList: any = productList.selectProductList.split(',');
    let selectProductList: any = [];
    const buyProductList: any = [];
    let totalPrice = 0;
    let list = selectProductIdList.reduce((obj, name) => {
      if (name in obj) {
        obj[name]++;
      } else {
        obj[name] = 1;
      }
      return obj;
    }, {});
    for (let i in list) {
      const child: any = {};
      child.id = i;
      child.num = list[i];
      selectProductList.push(child);
    }
    for (const item of selectProductList) {
      const product = await getDetailFromProductId(item);
      buyProductList.push(product);
    }
    buyProductList.forEach(item => {
      totalPrice += item.price * item.num
    })
    setTotalPrice(totalPrice);
    setSelectProductList(buyProductList);
  }

  //根据ID查询获取商品详细信息
  const getDetailFromProductId = async (item) => {
    const product = await request({
      url: apis.GET_PRODUCT_BY_ID,
      method: 'GET',
      data: {
        id: item.id,
      }
    });
    product.num = item.num;
    return product;
  }

  const btnHere = () => {
    setDinnerMethod(1);
  }

  const btnBale = () => {
    setDinnerMethod(0);
  }

  const toSelectAddress = () => {
    if (JSON.stringify(globalData.userInfo) == "{}") {
      Taro.showToast({
        icon: 'none',
        title: "请先登录/注册"
      });
      return;
    }
    Taro.navigateTo({
      url: '../select_address/select_address',
    })
    setCanSelectAddressBackListener(res => {
      setDeliveryAddressDetail(res.address);
    })
  };

  const inputDetail = (e) => {
    const str = e.detail.value;
    setInputCount(str.length);
    setDetail(str);
  };

  const payAction = () => {
    if (JSON.stringify(globalData.userInfo) == "{}") {
      Taro.showModal({
        title: "提示",
        content: "请先登录/注册",
        success: (res) => {
          if (res.confirm) {
            Taro.navigateTo({
              url: "../login/login",
            })
          }
        }
      })
      return;
    }
    let data: any = {};
    if (dinnerMethod === 1) {
      data.customerId = globalData.userInfo.id;
      data.customerName = globalData.userInfo.name;
      data.phone = globalData.userInfo.phone;
      data.customerAddress = '';
    } else {
      data.customerId = deliveryAddressDetail.customerId;
      data.customerName = deliveryAddressDetail.customerName;
      data.phone = deliveryAddressDetail.phone;
      data.customerAddress = deliveryAddressDetail.address;
    }
    data.title = selectProductList[0].name + "等" + selectProductList.length + "件商品";
    data.payment = totalPrice;
    data.orderStatus = "UNFIN";
    data.waimai = dinnerMethod;
    data.notes = detail;
    data.isGoOut = 0;
    request({
      url: apis.CREATE_ORDER,
      data: data,
      method: 'POST',
      pureData: false,
    }).then(res => {
      let data = JSON.stringify(res.data);
      Taro.redirectTo({
        url: `../order_detail/order_detail?data=${encodeURIComponent(data)}`
      })
    });
    request({
      url: apis.ADD_ORDERS_PRODUCT,
      data: selectProductList,
      method: "POST",
      pureData: false,
    }).then(res => {
      if (res.code === 200) {
        return;
      }
    })
  }


  return (
    <View className="container" style={{width: "100%", height: "100%"}}>
      <View className={styles.scroll_main}>
        <View className={styles.dinner_method}>
          <View>请选择就餐方式</View>
          <View className={styles.dinner_method_header}>
            <View style={{
              backgroundColor: dinnerMethod ? '#FF7F50' : " white",
              color: dinnerMethod ? 'white' : "black",
              borderColor: dinnerMethod ? 'orangered' : "orangered"
            }} onClick={btnHere}
                  className={styles.dinner_method_box}>
              <View>堂食</View>
              <Image style={{width: "100rpx", height: "100rpx"}} src={require("../../assets/store.png")}/>
            </View>

            <View style={{
              backgroundColor: dinnerMethod ? 'white' : " orangered",
              color: dinnerMethod ? 'black' : "white",
              borderColor: dinnerMethod ? '#888888' : "orangered"
            }} onClick={btnBale} className={styles.dinner_method_box}>
              <View>外卖</View>
              <Image style={{width: "120rpx", height: "120rpx"}} src={require("../../assets/bale.png")}/>
            </View>

          </View>
        </View>

        <View onClick={toSelectAddress} className={`${styles.address_btn} item-click`}
              style={{display: dinnerMethod ? 'none' : 'flex'}}>
          <Text>{deliveryAddressDetail.address ? deliveryAddressDetail.address : '选择地址'}</Text>
          <Text className="arrow_right"/>
        </View>

        <View className={styles.order}>
          <View>店内点单</View>
          <View style={{width: "90vw"}} className="divide-1-dark"/>
          {selectProductList.map(item => {
            return (
              <View>
                <View className={styles.order_list}>

                  <View style={{display: "flex", flex: "3"}}>
                    <Image style={{width: "120rpx", height: "120rpx"}}
                           src={item.imagePath === null || item.imagePath === '' ? require("../../assets/bale.png") : item.imagePath}/>
                    <View>{item.name}</View>
                  </View>

                  <View className={styles.order_num}>
                    <View className="text-tiny color-third-text">x{item.num}</View>
                    <View style={{width: "10rpx", textAlign: "center"}}>￥{item.num * item.price}</View>
                  </View>
                </View>
                <View style={{width: "100%"}} className="divide-1-dark"/>
              </View>
            )
          })}
          <View style={{marginLeft: "75%", display: "flex", marginTop: "20rpx"}}>
            <View className="text-tiny">实付</View>
            <View style={{fontWeight: "bold"}}>￥{totalPrice}</View>
          </View>
        </View>

        <View className={styles.pay_method}>
          <View>
            <View style={{marginLeft: "20rpx"}}>支付方式</View>
            <View style={{width: "100%"}} className="divide-1-dark"/>
          </View>

          <View className={styles.weChat_pay}>
            <View style={{display: "flex"}}>
              <Image style={{width: "40rpx", height: "40rpx"}} src={require("../../assets/weChatPay.png")}/>
              <View style={{marginLeft: "10rpx"}}>微信支付</View>
            </View>
            <Checkbox disabled={true} value={"weChat"} checked={true}/>
          </View>
        </View>

        <View className={styles.notes}>
          <Textarea className={styles.text_area} onInput={(e) => {
            inputDetail(e)
          }} value={detail} maxlength={50} placeholder={"可输入备注要求"}/>
          <View style={{display: "flex", justifyContent: "flex-end"}}>{inputCount}/50</View>
        </View>

      </View>

      <View className={styles.order_foot}>
        <View style={{display: "flex", marginLeft: "30rpx"}}>
          <Text>￥</Text>
          <Text style={{fontSize: "38rpx", fontWeight: "bold"}}>{totalPrice}</Text>
        </View>

        <View onClick={payAction} className={styles.soon_pay}>
          <Text style={{marginTop: "20rpx", marginBottom: "20rpx"}}>立即支付</Text>
        </View>
      </View>
    </View>
  )
};
export default order_submit;
